package org.zht.dormpro.auth.service.impl;

import com.xiaoleilu.hutool.util.CollectionUtil;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zht.dormpro.auth.bean.Tree;
import org.zht.dormpro.auth.mapper.SysDeptMapper;
import org.zht.dormpro.auth.model.SysDept;
import org.zht.dormpro.auth.service.IDeptService;
import org.zht.dormpro.pub.util.BuildTree;
import org.zht.dormpro.pub.util.ShiroUtil;

import java.util.ArrayList;
import java.util.List;

@Service
public class DeptServiceImpl implements IDeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Override
    public Tree<SysDept> listDeptTree() {
        List<Tree<SysDept>> trees = new ArrayList<>();
        List<SysDept> sysDepts = listDept();
        if(CollectionUtil.isNotEmpty(sysDepts)){
            Tree<SysDept> tree = null;
            for (SysDept sysDept : sysDepts) {
                tree = new Tree<>();
                tree.setId(sysDept.getId());
                tree.setText(sysDept.getName());
                tree.setParentId(sysDept.getParentId());
                trees.add(tree);
            }
        }
        Tree<SysDept> sysDeptTree = BuildTree.buildTreeList(trees);
        return sysDeptTree;
    }
    @Override
    public List<SysDept> listDept(){
        List<SysDept> sysDepts = sysDeptMapper.getAll();
        return sysDepts;
    }

    @Override
    public SysDept getDeptById(Integer id) {
        SysDept dept = sysDeptMapper.selectByPrimaryKey(id);
        return dept;

    }

    @Override
    public boolean addDept(SysDept dept) {
        //设置其他参数
        dept.setCreateTime(System.currentTimeMillis());
        dept.setModifyTime(System.currentTimeMillis());
        dept.setCreator(ShiroUtil.getAuthUser().getUserId());
        dept.setMender(ShiroUtil.getAuthUser().getUserId());
        int i = sysDeptMapper.insertSelective(dept);
        return i>0;
    }

    @Override
    public boolean editDept(SysDept newDept) {
        newDept.setMender(ShiroUtil.getAuthUser().getUserId());
        newDept.setModifyTime(System.currentTimeMillis());
        int i = sysDeptMapper.updateByPrimaryKeySelective(newDept);
        return i>0;
    }

    @Override
    public boolean deleteDept(@NonNull Integer deptId) {
        int i = sysDeptMapper.deleteByPrimaryKey(deptId);
        //删除其子菜单
        if (i > 0) {
            List<SysDept> sysPermissions = sysDeptMapper.selectByParentId(deptId);
            if(CollectionUtil.isNotEmpty(sysPermissions)){
                i = sysDeptMapper.deleteByParentId(deptId);
            }
        }
        return i>0;
    }
}
